package cn.iocoder.boot.springai001.controller;

import cn.iocoder.boot.springai001.entity.ChatSession;
import cn.iocoder.boot.springai001.service.ISessionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 会话管理控制器
 * <p>
 * 专注于会话的创建、查询、管理功能
 * 对话功能已迁移至 ChatController
 * <p>
 * 改进点：
 * 1. userId 和 sessionId 独立存储
 * 2. 支持多种查询方式
 * 3. 便于扩展到数据库
 * 4. 更符合领域驱动设计
 * 5. 职责更加清晰（只管理会话，不处理对话）
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/v1/sessions")
@Tag(name = "会话管理", description = "提供完善的会话管理功能")
public class SessionController {

    @Resource
    private ISessionService sessionService;

    /**
     * 创建新会话
     */
    @Operation(
            summary = "创建新会话",
            description = "为用户创建一个新的对话会话"
    )
    @PostMapping
    public ChatSession createSession(
            @Parameter(description = "用户ID")
            @RequestParam String userId,
            @Parameter(description = "会话名称")
            @RequestParam(defaultValue = "默认会话") String sessionName,
            @Parameter(description = "会话类型: general/file/web/data")
            @RequestParam(defaultValue = "general") String sessionType) {

        log.info("创建会话 - 用户: {}, 名称: {}, 类型: {}", userId, sessionName, sessionType);

        return sessionService.createSession(userId, sessionName, sessionType);
    }

    /**
     * 获取用户的所有会话（✅ 查询方便）
     */
    @Operation(
            summary = "获取用户会话列表",
            description = "查询指定用户的所有会话，按最后活跃时间排序"
    )
    @GetMapping("/user/{userId}")
    public Map<String, Object> getUserSessions(
            @Parameter(description = "用户ID")
            @PathVariable String userId) {

        log.info("查询用户会话 - userId: {}", userId);

        List<ChatSession> sessions = sessionService.getUserSessions(userId);

        // 为每个会话添加消息数量
        List<Map<String, Object>> sessionList = sessions.stream()
                .map(session -> {
                    int messageCount = sessionService.getMessageCount(session.getConversationId());
                    return Map.<String, Object>of(
                            "sessionId", session.getSessionId(),
                            "sessionName", session.getSessionName(),
                            "sessionType", session.getSessionType(),
                            "messageCount", messageCount,
                            "createdAt", session.getCreatedAt().toString(),
                            "lastActiveAt", session.getLastActiveAt().toString(),
                            "pinned", session.getPinned()
                    );
                }).toList();

        return Map.of(
                "success", true,
                "userId", userId,
                "totalSessions", sessions.size(),
                "sessions", sessionList
        );
    }

    /**
     * 获取特定会话详情
     */
    @Operation(
            summary = "获取会话详情",
            description = "查询指定会话的详细信息"
    )
    @GetMapping("/{sessionId}")
    public Map<String, Object> getSession(
            @Parameter(description = "会话ID")
            @PathVariable String sessionId) {

        log.info("查询会话详情 - sessionId: {}", sessionId);

        return sessionService.getSession(sessionId)
                .map(session -> {
                    int messageCount = sessionService.getMessageCount(session.getConversationId());
                    return Map.<String, Object>of(
                            "success", true,
                            "session", session,
                            "messageCount", messageCount
                    );
                })
                .orElse(Map.of(
                        "success", false,
                        "message", "会话不存在"
                ));
    }

    /**
     * 按类型筛选会话（✅ 查询方便）
     */
    @Operation(
            summary = "按类型筛选会话",
            description = "查询用户指定类型的所有会话"
    )
    @GetMapping("/user/{userId}/type/{sessionType}")
    public Map<String, Object> getSessionsByType(
            @Parameter(description = "用户ID")
            @PathVariable String userId,
            @Parameter(description = "会话类型")
            @PathVariable String sessionType) {

        log.info("按类型查询会话 - userId: {}, type: {}", userId, sessionType);

        List<ChatSession> sessions = sessionService.getSessionsByType(userId, sessionType);

        return Map.of(
                "success", true,
                "userId", userId,
                "sessionType", sessionType,
                "totalSessions", sessions.size(),
                "sessions", sessions
        );
    }

    /**
     * 搜索会话（✅ 查询方便）
     */
    @Operation(
            summary = "搜索会话",
            description = "根据关键词搜索用户的会话"
    )
    @GetMapping("/user/{userId}/search")
    public Map<String, Object> searchSessions(
            @Parameter(description = "用户ID")
            @PathVariable String userId,
            @Parameter(description = "搜索关键词")
            @RequestParam String keyword) {

        log.info("搜索会话 - userId: {}, keyword: {}", userId, keyword);

        List<ChatSession> sessions = sessionService.searchSessions(userId, keyword);

        return Map.of(
                "success", true,
                "userId", userId,
                "keyword", keyword,
                "totalResults", sessions.size(),
                "sessions", sessions
        );
    }

    /**
     * 获取最近活跃的会话（✅ 查询方便）
     */
    @Operation(
            summary = "获取最近活跃会话",
            description = "查询用户最近使用的会话"
    )
    @GetMapping("/user/{userId}/recent")
    public Map<String, Object> getRecentSessions(
            @Parameter(description = "用户ID")
            @PathVariable String userId,
            @Parameter(description = "返回数量")
            @RequestParam(defaultValue = "10") int limit) {

        log.info("查询最近活跃会话 - userId: {}, limit: {}", userId, limit);

        List<ChatSession> sessions = sessionService.getRecentActiveSessions(userId, limit);

        return Map.of(
                "success", true,
                "userId", userId,
                "sessions", sessions
        );
    }

    /**
     * 置顶/取消置顶会话
     */
    @Operation(
            summary = "置顶会话",
            description = "设置会话是否置顶"
    )
    @PutMapping("/{sessionId}/pin")
    public Map<String, Object> pinSession(
            @Parameter(description = "会话ID")
            @PathVariable String sessionId,
            @Parameter(description = "是否置顶")
            @RequestParam boolean pinned) {

        sessionService.pinSession(sessionId, pinned);

        return Map.of(
                "success", true,
                "sessionId", sessionId,
                "pinned", pinned
        );
    }

    /**
     * 删除会话
     */
    @Operation(
            summary = "删除会话",
            description = "删除指定的会话及其聊天历史"
    )
    @DeleteMapping("/{sessionId}")
    public Map<String, Object> deleteSession(
            @Parameter(description = "会话ID")
            @PathVariable String sessionId,
            @Parameter(description = "用户ID（用于权限验证）")
            @RequestParam String userId) {

        boolean success = sessionService.deleteSession(userId, sessionId);

        return Map.of(
                "success", success,
                "sessionId", sessionId,
                "message", success ? "会话已删除" : "删除失败，会话不存在或无权限"
        );
    }

    /**
     * 用户统计信息（✅ 查询方便）
     */
    @Operation(
            summary = "用户统计",
            description = "获取用户的会话统计信息"
    )
    @GetMapping("/user/{userId}/stats")
    public Map<String, Object> getUserStats(
            @Parameter(description = "用户ID")
            @PathVariable String userId) {

        log.info("查询用户统计 - userId: {}", userId);

        Map<String, Object> stats = sessionService.getUserStatistics(userId);

        return Map.of(
                "success", true,
                "userId", userId,
                "statistics", stats
        );
    }

    /**
     * 获取会话的聊天记录
     */
    @Operation(
            summary = "获取会话聊天记录",
            description = "查询指定会话的完整聊天历史，支持分页"
    )
    @GetMapping("/{sessionId}/messages")
    public Map<String, Object> getSessionMessages(
            @Parameter(description = "会话ID")
            @PathVariable String sessionId,
            @Parameter(description = "用户ID（用于权限验证）")
            @RequestParam(defaultValue = "2000") String userId,
            @Parameter(description = "页码，从1开始")
            @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量")
            @RequestParam(defaultValue = "20") int size) {

        log.info("查询会话聊天记录 - userId: {}, sessionId: {}, page: {}, size: {}", userId, sessionId, page, size);

        return sessionService.getSession(sessionId)
                .map(session -> {
//                    // 权限校验：仅允许会话所属用户访问
//                    if (!Objects.equals(session.getUserId(), userId)) {
//                        return Map.of(
//                                "success", false,
//                                "message", "无权限访问该会话"
//                        );
//                    }
                    // 获取所有消息（按时间正序：最早在前）
                    List<org.springframework.ai.chat.messages.Message> allMessages =
                            sessionService.getSessionMessages(sessionId);

                    // 分页（基于正序列表）
                    int start = (page - 1) * size;
                    int end = Math.min(start + size, allMessages.size());

                    List<org.springframework.ai.chat.messages.Message> pagedMessages =
                            start < allMessages.size() ?
                                    allMessages.subList(start, end) :
                                    Collections.emptyList();

                    // 转换为返回格式
                    List<Map<String, Object>> messages = pagedMessages.stream()
                            .map(msg -> {
                                Map<String, Object> messageData = new HashMap<>();
                                messageData.put("role", msg.getMessageType().getValue());
                                messageData.put("content", msg.getText());
                                messageData.put("metadata", msg.getMetadata());
                                return messageData;
                            })
                            .toList();

                    return Map.of(
                            "success", true,
                            "sessionId", sessionId,
                            "sessionName", session.getSessionName(),
                            "userId", userId,
                            "page", page,
                            "size", size,
                            "totalMessages", allMessages.size(),
                            "totalPages", (int) Math.ceil((double) allMessages.size() / size),
                            "messages", messages
                    );
                })
                .orElse(Map.of(
                        "success", false,
                        "message", "会话不存在"
                ));
    }

    /**
     * 清空会话聊天记录
     */
    @Operation(
            summary = "清空会话",
            description = "删除指定会话的所有聊天历史"
    )
    @DeleteMapping("/{sessionId}/clear")
    public Map<String, Object> clearSession(
            @Parameter(description = "会话ID")
            @PathVariable String sessionId) {

        log.info("清空会话 - sessionId: {}", sessionId);

        sessionService.clearSessionHistory(sessionId);

        return Map.of(
                "success", true,
                "sessionId", sessionId,
                "message", "会话聊天记录已清空"
        );
    }
}

